#include <stdio.h> 
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include "method_get.h"

int main(void)
{
    printf("Content-type: text/html;charset=utf-8\n\n");
    printHTMLHead();   
    int n, i;
    char * data;
    n = atoi(getenv("CONTENT_LENGTH"));
    data = (char *)malloc(n + 2);
    memset(data, '\0', n + 2);
    for(i = 0; i < (n + 1); ++i)
    {
        data[i] = getchar();
    }
	char lastName[255];
	char eMail[255];
	char reEmail[255];
	char password[255];
	char sex[255];
	char day[255];
	char month[255];
	char year[255];
	getFormData(data, lastName, eMail, reEmail, password, sex, day, month, year);
	if(checkInput(lastName, eMail, reEmail, password, sex, day, month, year) == 1)
	{
		printHTMLEnd();
		free(data);
		return 1;
	}
	char * filename = malloc(strlen(reEmail) + 5);;
	strcpy(filename, reEmail);
	strcat(filename, ".txt");
	FILE * File = fopen(filename, "wb");
	if(File == NULL)
	{
		printf("<h1>File opening error!</h1>\n");
		printHTMLEnd();
		free(data);
		return 1;
	}
	printDataToFile(File, lastName, eMail, reEmail, password, sex, day, month, year);
    printHTMLEnd();
    free(data);
	free(filename);
	if (File != NULL)
	{
		File = NULL;
	}
    return 0;
}